const gulp = require('gulp')
const minimist = require('minimist')
const connect = require('gulp-connect')
const path = require('path')
const open = require('open')
const { getPort } = require('./lib/utils')

const argv = minimist(process.argv.slice(2))
const buildHtml = require('./lib/index')

const docxPath = argv['docx-path']
const outputPath = argv['output-path']

const outputUrl = path.parse(outputPath)

const dir = outputUrl.dir

const isDev = process.env.NODE_ENV === 'development'
let scss = null;

if (isDev) {
  scss = require('gulp-sass')(require('sass'));
}

//console.log(docxPath, outputPath, outputUrl)

gulp.task('watch_docx', function () {
  gulp.watch(docxPath, gulp.series(['build_html', 'reload']))
})

gulp.task('build_html', function (done) {
  buildHtml(docxPath, outputPath).then((res) => done())
})

// 监听scss文件
gulp.task('watch_scss', function (done) {
  if (isDev) {
    return gulp.watch('src/scss/*.scss', gulp.series('build_scss','build_html','reload'));
  } else {
    done();
  }
	
});

// 构建css
gulp.task('build_scss', function () {
	return gulp.src('src/scss/*.scss').pipe(scss()).pipe(gulp.dest('./lib/'));
});


gulp.task('connect',  function () {
  Promise.all([getPort(),getPort(30000, 40000)]).then(([port,websocketPort])=>{
    const host = 'localhost'
    connect.server(
      {
        host,
        root: dir,
        port,
        livereload: {
          port: websocketPort,
        },
      },
      function () {
        open(`http://${host}:${port}/${outputUrl.base}`)
      }
    )
  })
})

// 刷新服务器
gulp.task('reload', function () {
  return gulp.src(dir).pipe(connect.reload())
})


gulp.task('dev', function(){
  let task = isDev ? gulp.parallel('watch_scss','watch_docx', 'connect') : gulp.parallel('watch_docx', 'connect');
   gulp.series(['build_html', task])()
})

